package com.swak.persistence.mybatis.enhance;

import org.apache.ibatis.binding.BindingException;
import org.apache.ibatis.binding.MapperProxyFactory;
import org.apache.ibatis.binding.MapperRegistry;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
import org.apache.ibatis.session.Configuration;

import com.swak.persistence.mybatis.injector.SqlInjector;

/**
 * 增强 Mapper 注入: 基本直接复制 MapperRegistry
 * 
 * @author lifeng
 * @date 2021年1月21日 下午3:34:20
 */
public class EnhanceMapperRegistry extends MapperRegistry {

	private SqlInjector sqlInjector;

	public EnhanceMapperRegistry(Configuration config) {
		super(config);
		this.sqlInjector = new SqlInjector();
	}

	/**
	 * 在默认的 Mapper 的基础上，提供基础的CURD， 自动解析CURD的 SQL
	 */
	@Override
	public <T> void addMapper(Class<T> type) {
		if (type.isInterface()) {
			if (hasMapper(type)) {
				throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
			}
			boolean loadCompleted = false;
			try {
				knownMappers.put(type, new MapperProxyFactory<>(type));
				// It's important that the type is added before the parser is run
				// otherwise the binding may automatically be attempted by the
				// mapper parser. If the type is already known, it won't try.
				MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type) {
					@Override
					protected void postParse(MapperBuilderAssistant assistant) {
						sqlInjector.inspectInject(assistant, type);
					}
				};
				parser.parse();
				loadCompleted = true;
			} finally {
				if (!loadCompleted) {
					knownMappers.remove(type);
				}
			}
		}
	}
}